# -*- coding:utf-8 -*-


import time
import json
import config
import pymongo
from scrapy import Spider
from scrapy.http import Request


class OkcoinExchange(Spider):
    name = 'okcoin'

    def __init__(self, name=None, **kwargs):
        super(OkcoinExchange, self).__init__(name, **kwargs)

        self.pairs = ['btc_usd', 'ltc_usd', 'eth_usd', 'etc_usd', 'bch_usd']

        # 连接mongodb
        # client = pymongo.MongoClient('localhost', 27017)
        client = pymongo.MongoClient('47.254.26.182', 27017)
        self.db = client.bt_news

    def start_requests(self):
        for pair in self.pairs:
            url = 'https://www.okcoin.com/api/v1/ticker.do?symbol=%s' % pair

            yield Request(
                url=url,
                dont_filter=True,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
                },
                meta={

                },
                callback=self.exchange_info
            )

    def exchange_info(self, response):
        # 获取json中的数据，对应交易所信息
        body = json.loads(response.body)
        ticker = body.get('ticker')

        okcoin_url = response.url
        # 交易对
        exchange_pair = okcoin_url.split('=')[1]
        pair = exchange_pair.split('_')
        pair_name = str(pair[0]).upper()
        variual_pair = str(pair[1]).upper()

        self.log(pair_name)
        self.log(variual_pair)

        name = ['okcoin','okex']
        for exchange in name:
            # 交易所名称
            exchange_name = exchange

            # 买家
            buy = ticker.get('buy')

            # 卖价
            sell = ticker.get('sell')

            # 最高价
            high = ticker.get('high')

            # 最低价
            low = ticker.get('low')

            # 成交量
            vol = ticker.get('vol')

            # 时间
            okcoin_time = body.get('date')

            # 最新成交价
            last = ticker.get('last')

            # 入库mongo
            data = {
                'exchange_name': exchange_name,
                'variual_coin_name': pair_name,
                'variual_pair': variual_pair,
                # 'market_value': market_value,
                'buy': buy,
                'sell': sell,
                'high': high,
                'low': low,
                'last': last,
                'vol': vol,
                'time': okcoin_time,
                # 'roportion': roportion,
                # 'hasklin': hasklin,
                # 'change1d': change1d,
                'updatetime': time.localtime()
            }

            # pairs = [pair_name, variual_pair]
            # for pair in pairs:
            #     display_name = pair
            #
            #     data_pair = {
            #         'display_name': display_name
            #     }
            #
            #     self.db.bt_virtual_coin.update_one(
            #         {'display_name': display_name},
            #         {'$set': data_pair}, upsert=True)

            # 入库mongo
            if response.status == 200:
                self.db.bt_coin.update_one({'exchange_name': exchange_name, 'variual_coin_name': pair_name, 'variual_pair': variual_pair},
                                           {'$set': data}, upsert=True)


        # 循环更新数据
        url = response.url
        yield Request(
            url=url,
            dont_filter=True,
            headers={
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
            },
            meta={

            },
            callback=self.exchange_info
        )


'''
每三秒更新mongo中的数据
'''